package org.biz.modules.controller;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfWriter;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.biz.common.*;
import org.biz.modules.entity.*;
import org.biz.modules.service.SysRoleService;
import org.biz.modules.service.SysUserService;
import org.biz.util.ExcelUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @author zf
 * @ClassName SysUserController
 */
@RestController
@RequestMapping("/api/sys")
public class SysUserController {

    @Resource
    private SysUserService sysUserService;
    @Resource
    private SysRoleService sysRoleService;

    @Value("${data.year}")
    private String dataYear;


    /**
     *学员分页列表
     ***/
    @GetMapping("/page")
    @ApiOperation(value = "学员分页列表")
//    @PreAuthorize("hasRole('ADMIN')")
    public Result<?> page(QueryParams queryParams,
                          @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                          @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize){
        Result<?> x = getQueryAuth(queryParams);
        if (x != null) return x;
        Page<SysUser> page = new Page<>(pageNo, pageSize);
        IPage<SysUser> pageList = sysUserService.getPage(page, queryParams);
        return Result.OK(pageList);
    }

    @GetMapping("/export")
    @ApiOperation(value = "导出学员列表")
    public Result<?> export(QueryParams queryParams,HttpServletResponse response){
        Result<?> x = getQueryAuth(queryParams);
        if (x != null) return x;
        List<SysUser> exportList = sysUserService.getExportList(queryParams);
        try {
            ExcelUtils.exportToExcel(exportList, SysUser.class,"学员信息表.xlsx", response);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private Result<?> getQueryAuth(QueryParams queryParams) {
        String userId = queryParams.getUserId();
        if (StringUtils.isBlank(userId)) {
            return Result.error("当前登录用户ID不能为空！");
        }
        List<SysRole> roleList = sysRoleService.getRoleListByUserId(userId);
        Map<String, String> roleMap = roleList.stream().collect(Collectors.toMap(SysRole::getRoleCode, SysRole::getAuth));
        //超级管理员 看所有数据
        if (roleMap.containsKey(CommonConstant.SUPER_ADMIN)){
            //置空 查看所有数据
            queryParams.setAuth("");
        }
        //管理员 看自己(多个)专科的数据
        else if (roleMap.containsKey(CommonConstant.ADMIN)) {
            //管理员对应的所有专科
            String auth = MapUtils.getString(roleMap, CommonConstant.ADMIN);
            queryParams.setAuth(auth);
        }else{
            return Result.error("非管理员，无权限查看！");
        }
        queryParams.setDataYear(dataYear);
        return null;
    }


    /**
     *学员信息详情
     ***/
    @GetMapping("/getUserInfoById")
    @ApiOperation(value = "学员信息详情",response = UserDetailVO.class)
    public Result<?> getUserInfo(@RequestParam("userId") String userId) {
        if (StringUtils.isBlank(userId)) {
            return Result.error("用户ID不能为空！");
        }
        UserDetailVO vo = new UserDetailVO();
        SysUser user = sysUserService.getById(userId);
//        setHospitalCity(user);
        vo.setSysUser(user);
        //管理员可看填报详情
//        boolean admin = sysUserService.isAdmin(userId);
//        if (admin) {
            //管理员查看填报详情
            List<SysDocUser> titleText = sysUserService.getTitleText("", userId);
            vo.setDocInfoList(titleText);
//        }
        return Result.OK(vo);
    }

    private void setHospitalCity(SysUser user) {
        //单位
        String hospital = user.getHospital();
        if (StringUtils.isNotBlank(hospital)) {
            List<SysHospital> departmentList = sysUserService.getHospitalList("",hospital);
            if (CollectionUtils.isNotEmpty(departmentList)) {
                user.setHospitalCity(departmentList.get(0).getCity());
            }
        }
        //取证时的单位
        String hospitalHistory = user.getHospitalHistory();
        if (StringUtils.isNotBlank(hospitalHistory)) {
            List<SysHospital> departmentList = sysUserService.getHospitalList("",hospitalHistory);
            if (CollectionUtils.isNotEmpty(departmentList)) {
                user.setHospitalCityHistory(departmentList.get(0).getCity());
            }
        }
    }

    /**
     *导出填报word
     ***/
    @GetMapping("/exportWord")
    @ApiOperation(value = "导出填报word")
    public Result<?> exportWord(String userId, HttpServletRequest request, HttpServletResponse response) throws Exception {
        SysUser user = sysUserService.getById(userId);
//        setHospitalCity(user);
        if (StringUtils.isBlank(user.getName()) ||
                StringUtils.isBlank(user.getIdCard()) ||
                StringUtils.isBlank(user.getMobile()) ||
                StringUtils.isBlank(user.getSex()) ||
                user.getAge() == null ||
                StringUtils.isBlank(user.getDepartment()) ||
                StringUtils.isBlank(user.getBaseHospital()) ||
                StringUtils.isBlank(user.getTrainYear()) ||
                StringUtils.isBlank(user.getCertificateDate()) ||
                StringUtils.isBlank(user.getCertificateNum())
        ){
            return Result.error("请填写完整学员基本信息的姓名、身份证、手机号等信息再下载！");
        }
        if (StringUtils.isBlank(user.getHospitalHistory()) ||
                StringUtils.isBlank(user.getHospitalCityHistory()) ||
                StringUtils.isBlank(user.getTitleHistory()) ||
                StringUtils.isBlank(user.getDutyHistory()) ||
                StringUtils.isBlank(user.getEducationLevelHistory()) ||
                StringUtils.isBlank(user.getDegreeHistory()) ||
                StringUtils.isBlank(user.getStationHistory())
        ){
            return Result.error("请填写完整取证信息再下载！");
        }
        if (StringUtils.isBlank(user.getHospital()) ||
                StringUtils.isBlank(user.getHospitalCity()) ||
                StringUtils.isBlank(user.getTitle()) ||
                StringUtils.isBlank(user.getDuty()) ||
                StringUtils.isBlank(user.getEducationLevel()) ||
                StringUtils.isBlank(user.getDegree()) ||
                StringUtils.isBlank(user.getStation())
        ){
            return Result.error("请填写完整目前就职信息再下载！");
        }
        Map<String, Object> userMap = PropertyUtils.describe(user);
        //有null值的，替换成空字符串，保证word模版占位符被替换
        userMap.replaceAll((key, value) -> value == null ? "" : value);
        //四大项填报模板
        List<SysDocTitle> titleList = sysUserService.getDocTitleList(userId);
        //当前用户所有填报信息
        List<SysDocUser> titleText = sysUserService.getTitleText("", userId);
        //按四项分组
        Map<String, List<SysDocUser>> titleMap = titleText.stream().collect(Collectors.groupingBy(SysDocUser::getTitleId));
        //向word添加填报项
        for (int i = 0; i < titleList.size(); i++) {
            String titleId = titleList.get(i).getId(); // 确保取的是正确的 titleId
            //标题下所有的填报信息
//            List<SysDocUser> docUsers = titleMap.get(String.valueOf(i + 1));
            List<SysDocUser> docUsers = titleMap.getOrDefault(titleId,new ArrayList<>());
            //标题下所有的已完成填报信息
            List<SysDocUser> docUserFinishList = new ArrayList<>();
            for (SysDocUser doc:docUsers) {
                //填空已完成
                if (doc.getFinishNum() == 1
                        || (StringUtils.equals(doc.getTitleId(),CommonConstant.FOUR) && doc.getTextIndex()==Integer.parseInt(CommonConstant.ONE)) //默认添加（四）专业发展：系统生成的第一条完成近5年内专科护士继续教育平台规定的课程和考核
                ){
                    String v1 = "_/_";
                    if (StringUtils.isNotBlank(doc.getValue1())) {
                        v1 = doc.getValue1();
                    }
                    String text = doc.getText().replace("$$", v1);
                    if (StringUtils.contains(text,"@@")){
                        String v2 = "_/_";
                        if (StringUtils.isNotBlank(doc.getValue2())) {
                            v2 = doc.getValue2();
                        }
                        text = text.replace("@@",v2);
                    }
                    doc.setText(text);
                    docUserFinishList.add(doc);
                }

            }
            List<String> testList = docUserFinishList.stream().map(SysDocUser::getText).collect(Collectors.toList());

            //填空和佐证材料描述
            userMap.put("list"+i,testList);
            //标题
            userMap.put("title"+i,CollectionUtils.isEmpty(docUserFinishList) ? "" : titleList.get(i).getTitle());
        }

        //根据模板生成文档
        String fileName = "信息填报汇总表.docx";
        WordUtils wordUtil = new WordUtils();
        try {
            List<String> testList = new ArrayList<String>();
            wordUtil.getWord2(userMap, testList, fileName, response);

        } catch (Exception e) {
            System.out.println("导出 Word 文件失败"+e);
            return Result.error("导出失败，请稍后重试！");
        }

        return null;
    }
    /**
     *如果承诺书和汇总表都上传了，则更新人员状态为待审核
     ***/
//    @PutMapping("/updateStatusByUserId")
//    @ApiOperation(value = "更新人员状态为待审核")
//    public Result<?> updateStatusByUserId(String userId) {
//        StatusVO statusVO = sysUserService.getFinishStatusByUserId(userId);
//        boolean finishPromise = statusVO.isFinishPromise();
//        boolean finishSummary = statusVO.isFinishSummary();
//        if (finishPromise && finishSummary) {
//            //如果承诺书和汇总表都上传了，则更新人员状态为待审核
//            UpdateWrapper<SysUser> updateWrapper = new UpdateWrapper<>();
//            updateWrapper.eq("id", userId);
//            updateWrapper.set("status", CommonConstant.UNAPPROVED);
//            updateWrapper.set("update_time", LocalDateTime.now());
//            boolean update = sysUserService.update(updateWrapper);
//            if (update) {
//                return Result.OK("更新成功！");
//            }else {
//                return Result.error("更新失败！");
//            }
//        }
//        return Result.OK();
//    }

    /**
     *获取填报完成状态、基本信息状态、承诺书、汇总表上传状态
     **/
    @GetMapping("/getFinishStatusByUserId")
    @ApiOperation(value = "获取填报完成状态、基本信息状态、承诺书、汇总表上传状态")
    public Result<?> getFinishStatusByUserId(String userId) {
        if (StringUtils.isBlank(userId)) {
            return Result.error("当前登录用户ID不能为空！");
        }
        StatusVO statusVO = sysUserService.getFinishStatusByUserId(userId);
        return Result.OK(statusVO);
    }



    /**
     *保存用户基本信息，上传证书、头像，
     ***/
    @Transactional(rollbackFor = Exception.class)
    @PutMapping("/updateUser")
    @ApiOperation(value = "保存用户基本信息，上传证书、头像")
    public Result<?> updateUser(@RequestBody SysUser sysUser) {
        String userId = sysUser.getId();
        if (StringUtils.isBlank(userId)) {
            return Result.error("当前登录用户ID不能为空！");
        }
        boolean update = sysUserService.isUpdate(userId);
        boolean admin = sysUserService.isAdmin(userId);
        //截止日期只针对普通学员，管理员不判断
        if (!update && !admin) {
            return Result.error("已过截止日期，信息不可提交！");
        }
        Result<?> edit = sysUserService.isEdit(userId);
        if (edit != null) {
            return edit;
        }
        sysUser.setUpdateTime(LocalDateTime.now());
        //根据医院添加城市
        setHospitalCity(sysUser);
        boolean b = sysUserService.updateById(sysUser);
        if (b) {
            updateStatus(userId);
            return Result.OK("保存成功！");
        }else {
            return Result.error("保存失败！");
        }
    }

    @PutMapping("/approve")
    @ApiOperation(value = "审批")
    public Result<?> approve(@RequestParam("userId") @ApiParam("学员ID") String userId,
                             @RequestParam("status") @ApiParam("审批意见（已通过/未通过）") String status) {
        if (StringUtils.isBlank(userId)) {
            return Result.error("学员ID不能为空！");
        }
        if (StringUtils.isBlank(status)) {
            return Result.error("审批意见不能为空！");
        }
        UpdateWrapper<SysUser> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", userId);
        updateWrapper.set("status", status);
        updateWrapper.set("update_time", LocalDateTime.now());
        //认证有效期，根据“通过”的时间，按年份+5
        if (CommonConstant.PASSED.equals(status)) {
            int expire = LocalDateTime.now().getYear() + 5;
            updateWrapper.set("expire", expire);

            //审批通过后，更新证书的实际生成日期，下载证书时用
            SysUser user = sysUserService.getById(userId);
            String dataYear = user.getDataYear();
            if (StringUtils.isNotBlank(user.getCertificateDateConfig())) {
                String certificateCreateDate = user.getCertificateDateConfig().replaceFirst("^\\d{4}", dataYear);
                updateWrapper.set("certificate_create_date", certificateCreateDate);
            }

        }
        sysUserService.update(updateWrapper);
        return Result.OK();
    }

    /**
    *
    *判断是否满足审批条件,满足则更新状态为"待审核"
     **/
    private void updateStatus(String userId) {
        StatusVO statusVO = sysUserService.getFinishStatusByUserId(userId);
        System.out.println(">>>>>>>>>>用户："+userId+"，"+statusVO.isFinishPromise()+statusVO.isFinishSummary()+statusVO.isFinishAllDoc()+statusVO.isFinishBaseInfo());
        if (statusVO.isFinishPromise() && statusVO.isFinishSummary() && statusVO.isFinishAllDoc() && statusVO.isFinishBaseInfo()) {
            UpdateWrapper<SysUser> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("id", userId);
            updateWrapper.set("status", CommonConstant.UNAPPROVED);
            updateWrapper.set("update_time", LocalDateTime.now());
            sysUserService.update(updateWrapper);
        }
    }

    /**
     *保存再认证信息填报
     ***/
    @PostMapping("/saveDoc")
    @ApiOperation(value = "保存或更新再认证信息填报")
    public Result<?> saveDoc(@RequestBody List<SysDocUser> doc) {
        if (CollectionUtils.isEmpty(doc)){
            return Result.error("未填写任何内容！");
        }
        SysDocUser docUser = doc.get(0);
        String userId = docUser.getUserId();
        if (StringUtils.isBlank(userId)) {
            return Result.error("当前登录用户ID不能为空！");
        }
        boolean update = sysUserService.isUpdate(userId);
        boolean admin = sysUserService.isAdmin(userId);
        //截止日期只针对普通学员，管理员不判断
        if (!update && !admin) {
            return Result.error("已过截止日期，信息不可提交！");
        }
        Result<?> edit = sysUserService.isEdit(userId);
        if (edit != null) {
            return edit;
        }
        Result<?> result = sysUserService.saveOrUpdate(doc, userId);
        if (result.isSuccess()) {
            updateStatus(userId);
        }
        return result;
    }



    /**
     *学员再认证填报-学习进度
     *
     * @param userId 登录人ID
     * @return 返回四个填报项文本、已填写数量、总数
     **/
    @GetMapping("/getDocTitleList")
    @ApiOperation(value = "学员再认证填报-学习进度")
    public Result<?> getDocTitleList(String userId) {
        if (StringUtils.isBlank(userId)) {
            return Result.error("当前登录用户ID不能为空！");
        }
        List<SysDocTitle> departmentList = sysUserService.getDocTitleList(userId);
        return Result.OK(departmentList);
    }

    /**
     *学员再认证填报-填报内容
     *
     * @param titleId 填报项id
     * @param userId 登录人ID
     * @return 返回填报内容文本和填报值
     **/
    @GetMapping("/getTitleTextList")
    @ApiOperation(value = "学员再认证填报-填报内容")
    public Result<?> getTitleTextList(String titleId,String userId) {
        if (StringUtils.isBlank(userId)) {
            return Result.error("当前登录用户ID不能为空！");
        }
        if (StringUtils.isBlank(titleId)) {
            return Result.error("填报项ID不能为空！");
        }
        List<SysDocUser> titleText = sysUserService.getTitleText(titleId, userId);
        return Result.OK(titleText);
    }



    /**
    *专科和基地下拉
    *
     * @param departName 专科名称
     * @return 传空时返回所有专科名称，传具体专科名称时返回对应的所有基地
     **/
    @GetMapping("/getDepartmentList")
    @ApiOperation(value = "专科和基地下拉")
    public Result<?> getDepartmentList(String departName) {
        List<SysItem> departmentList = sysUserService.getDepartmentList(departName);
        return Result.OK(departmentList);
    }


    /**
     *城市和医院下拉
     *
     * @param cityName 城市名称
     * @param name 医院名称
     * @return 传空时返回所有城市名称，传城市名称时返回对应的所有医院
     **/
    @GetMapping("/getHospitalList")
    @ApiOperation(value = "城市和医院下拉")
    public Result<?> getHospitalList(String cityName,String name) {
        List<SysHospital> departmentList = sysUserService.getHospitalList(cityName,name);
        return Result.OK(departmentList);
    }

    /**
     *审核状态下拉
     *
     **/
    @GetMapping("/getStatusList")
    @ApiOperation(value = "审核状态下拉")
    public Result<?> getStatusList() {
        List<Map<String, String>> statusMapList = new ArrayList<>();
        List<String> statusList = Arrays.asList(CommonConstant.STATUS);
        for (String status: statusList) {
            Map<String, String> map = new HashMap<>();
            map.put("label",status);
            map.put("value",status);
            statusMapList.add(map);
        }
        return Result.OK(statusMapList);
    }



    /**
     *更新截止日期
     ***/
    @PutMapping("/updateDeadline")
    @ApiOperation(value = "更新截止日期")
    public Result<?> updateDeadline(String deadline) {
        if (StringUtils.isBlank(deadline)) {
            return Result.error("截止日期不能为空！");
        }
        int i = sysUserService.updateDeadline(deadline);
        if (i > 0) {
            return Result.OK("更新成功！");
        }else{
            return Result.error("更新失败！");
        }
    }


    /**
     *是否可编辑
     ***/
    @GetMapping("/isUpdate")
    @ApiOperation(value = "是否可编辑")
    public Result<?> isUpdate(String userId) {
        return Result.OK(sysUserService.isUpdate(userId));
    }


    @GetMapping("/getCountByStatus")
    @ApiOperation(value = "总体数据概览",response = UserCountVO.class)
    public Result<?> getCountByStatus(String name) {
        return Result.OK(sysUserService.getCountByStatus(name));
    }


    @GetMapping("/getLearningRecord/{idNumber}")
    @ApiOperation(value = "获取学习记录")
    public Result<List<LearningRecord>> getLearningRecord(@PathVariable(required = true) String idNumber) {
        return Result.OK(sysUserService.getLearningRecord(idNumber));
    }

    @PostMapping("/finishLearningRecord")
    @ApiOperation(value = "设为看完")
    public Result<?> finishLearningRecord(@RequestBody SetSubjectFinishReq req) {
        sysUserService.setSubjectFinish(req.getIdNumber(), req.getSubjectId());
        return Result.OK();
    }


    @GetMapping("/getDeadLine")
    @ApiOperation(value = "获取截止日期")
    public Result<?> getDeadLine() {
        return Result.OK("",sysUserService.getDeadLine());
    }

    @GetMapping("/getDepartmentUserCount")
    @ApiOperation(value = "人数柱状图-专科名称和护士数量",response = DepartmentUserCount.class)
    public Result<List<DepartmentUserCount>> getDepartmentUserCount() {
        return Result.OK(sysUserService.getDepartmentUserCount());
    }

    @GetMapping("/getCityUserCount")
    @ApiOperation(value = "人数柱状图-地市名称和护士数量",response = CityUserCount.class)
    public Result<List<CityUserCount>> getCityUserCount() {
        return Result.OK(sysUserService.getCityUserCount());
    }

    @PutMapping("/approveBack")
    @ApiOperation(value = "退回")
    public Result<?> approveBack(@RequestParam("userId") @ApiParam("学员ID") String userId) {
        if (StringUtils.isBlank(userId)) {
            return Result.error("学员ID不能为空！");
        }
        UpdateWrapper<SysUser> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", userId);
        updateWrapper.set("status", CommonConstant.UNFINISHED);
        updateWrapper.set("back", CommonConstant.BACK);
        updateWrapper.set("update_time", LocalDateTime.now());
        sysUserService.update(updateWrapper);
        return Result.OK();
    }

    @GetMapping("/getSexItemList")
    @ApiOperation(value = "获取性别下拉")
    public Result<List<String>> getSexItemList() {
        return Result.OK(Arrays.asList("男","女"));
    }
    @GetMapping("/getCity13List")
    @ApiOperation(value = "获取13城市下拉")
    public Result<List<String>> getCity13List() {
        return Result.OK(sysUserService.getCity13List());
    }

//    @GetMapping("/downloadCertificateByUserId")
//    @ApiOperation(value = "下载合格证书")
//    public Result<?> downloadCertificate(@RequestParam("userId") @ApiParam("学员ID") String userId,HttpServletResponse response){
//        if (StringUtils.isBlank(userId)) {
//            return Result.error("当前登录用户ID不能为空！");
//        }
//        SysUser user = sysUserService.getById(userId);
//        if (user == null){
//            return Result.error("用户查询异常，无法下载！");
//        }
//        if (!StringUtils.equals(CommonConstant.PASSED, user.getStatus())) {
//            return Result.error("用户未通过审核，无法下载！");
//        }
//        if (StringUtils.isBlank(user.getCertificateNum())){
//            return Result.error("证书编号为空，无法下载！");
//        }
//        if (StringUtils.isBlank(user.getDataYear())){
//            return Result.error("填报年份为空，无法下载！");
//        }
//        if (user.getExpire() == null) {
//            return Result.error("认证有效期为空，无法下载！");
//        }
//
//
//        try {
//            String certificateNum = user.getDataYear()+CertificateNumberUtils.processCertificateNum(user.getCertificateNum());
//            Map<String, Object> dataMap = new HashMap<>();
//            dataMap.put("certificateNum", certificateNum);
//            dataMap.put("name", user.getName());
//            dataMap.put("expire", user.getExpire().toString());
//            dataMap.put("dataYear", user.getDataYear());
//            // 可选：添加图片
//            dataMap.put("backgroundImage", "img/background.png");
//            dataMap.put("stampImage", "img/stamp.png");
//            // 导出PDF
//            WordUtil.exportPdf(response, dataMap, "certificate.ftl", "江苏省专科护士再认证合格证书.pdf");
//
//        } catch (Exception e) {
//            e.printStackTrace();
//            System.out.println("下载文件失败"+e);
//            return Result.error("下载失败，请稍后重试！");
//        }
//
//        return null;
//    }


    @GetMapping("/downloadCertificateByUserId")
    @ApiOperation(value = "下载合格证书")
    public Result<?> downloadCertificate(@RequestParam("userId") @ApiParam("学员ID") String userId, HttpServletResponse response) {
        if (StringUtils.isBlank(userId)) {
            return Result.error("当前登录用户ID不能为空！");
        }
        SysUser user = sysUserService.getById(userId);
        if (user == null) {
            return Result.error("用户查询异常，无法下载！");
        }
        if (!StringUtils.equals(CommonConstant.PASSED, user.getStatus())) {
            return Result.error("用户未通过审核，无法下载！");
        }
        if (StringUtils.isBlank(user.getCertificateNum())) {
            return Result.error("证书编号为空，无法下载！");
        }
        if (StringUtils.isBlank(user.getDataYear())) {
            return Result.error("填报年份为空，无法下载！");
        }
        if (user.getExpire() == null) {
            return Result.error("认证有效期为空，无法下载！");
        }

        try {

            //证书生成日期，如果实际生成日期有值，取实际的日期，否则取当年的日期
                String date = StringUtils.isNotBlank(user.getCertificateCreateDate()) ? user.getCertificateCreateDate() : user.getCertificateDateConfig();
            String dataYear = date.substring(0, 4);
            String certificateNum = dataYear + CertificateNumberUtils.processCertificateNum(user.getCertificateNum());

            // 使用ClassLoader获取资源，确保跨平台兼容性
            ClassLoader classLoader = getClass().getClassLoader();

            // 创建A3横向页面 (420mm × 297mm)
            Document document = new Document(PageSize.A3.rotate());
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            PdfWriter writer = PdfWriter.getInstance(document, baos);
            document.open();

            // 获取PDF内容底层对象
            PdfContentByte canvas = writer.getDirectContentUnder();

            // 添加背景图片
            try (InputStream bgStream = classLoader.getResourceAsStream("img/background.png")) {
                if (bgStream != null) {
                    Image background = Image.getInstance(IOUtils.toByteArray(bgStream));
                    background.scaleAbsolute(PageSize.A3.rotate().getWidth(), PageSize.A3.rotate().getHeight());
                    background.setAbsolutePosition(0, 0);
                    canvas.addImage(background);
                }
            }

            // 设置中文字体
//            BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            BaseFont bf = loadKaiFont(classLoader);
            // 绘制装饰边框
            drawBorder(canvas, PageSize.A3.rotate());

            // 开始绘制文本
            canvas.beginText();
            canvas.setFontAndSize(bf, 10);
            canvas.setColorFill(BaseColor.BLACK);

            // 页面尺寸
            float pageWidth = PageSize.A3.rotate().getWidth();
            float pageHeight = PageSize.A3.rotate().getHeight();

            // 绘制标题
            BaseFont bf2 = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            InputStream fontStream = classLoader.getResourceAsStream("fonts/SimHei.ttf");
            if (fontStream != null) {
                byte[] fontData = IOUtils.toByteArray(fontStream);
                bf2 = BaseFont.createFont("simhei.ttf", BaseFont.IDENTITY_H,
                        BaseFont.NOT_EMBEDDED, BaseFont.CACHED, fontData, null);
            }

            canvas.setFontAndSize(bf2, 62); // 约72px -> 42pt
            canvas.showTextAligned(Element.ALIGN_CENTER, "江苏省专科护士再认证合格证书",
                    pageWidth / 2, pageHeight - 220, 0);


            // 绘制证书编号（右上角）
            canvas.setFontAndSize(bf, 22); // 约28px -> 16pt
            canvas.showTextAligned(Element.ALIGN_RIGHT, "专护再字第 " + certificateNum + " 号",
                    pageWidth - 80, pageHeight - 330, 0);

            // 绘制正文内容
            canvas.setFontAndSize(bf, 26); // 约38px -> 22pt
            String line1 = user.getName() + "同志参加江苏省专科护士再认证，经审核合格，特发此证。";
            String line2 = "本证书有效期至" + user.getExpire().toString() + "年。";

            canvas.showTextAligned(Element.ALIGN_CENTER, line1,
                    pageWidth / 2, pageHeight - 380, 0);
            canvas.showTextAligned(Element.ALIGN_CENTER, line2,
                    pageWidth / 2, pageHeight - 430, 0);

            // 绘制页脚
            canvas.setFontAndSize(bf, 26); // 约26px -> 14pt
            canvas.showTextAligned(Element.ALIGN_CENTER, "江苏省护理学会印制",
                    pageWidth / 2, 90, 0);

            // 绘制印章文字
            canvas.setFontAndSize(bf, 22); // 约32px -> 16pt
            canvas.showTextAligned(Element.ALIGN_CENTER, "（江苏省护理学会印）",
                    pageWidth - 250, 200, 0);

            //日期
            canvas.showTextAligned(Element.ALIGN_CENTER, date,
                    pageWidth - 250, 150, 0);

            canvas.endText();

            // 添加印章图片
            try (InputStream stampStream = classLoader.getResourceAsStream("img/stamp.png")) {
                if (stampStream != null) {
                    Image stamp = Image.getInstance(IOUtils.toByteArray(stampStream));
                    stamp.scaleToFit(150, 150);
                    // 调整印章位置（右下角）
                    stamp.setAbsolutePosition(pageWidth - 320, 120);
                    document.add(stamp);
                }
            }

            document.close();

            // 设置响应头
            response.setContentType("application/pdf");
            response.setHeader("Content-Disposition", "attachment; filename=" +
                    new String("江苏省专科护士再认证合格证书.pdf".getBytes(), StandardCharsets.ISO_8859_1));
            // 写入响应流
            ServletOutputStream out = response.getOutputStream();
            baos.writeTo(out);
            out.flush();

        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("下载失败，请稍后重试！");
        }
        return null;
    }

    // 绘制装饰边框的方法
    private void drawBorder(PdfContentByte canvas, Rectangle pageSize) {
        float pageWidth = pageSize.getWidth();
        float pageHeight = pageSize.getHeight();

        // 绘制主边框
        canvas.setColorStroke(new BaseColor(0xc9, 0xa5, 0x6a)); // #c9a56a
        canvas.setLineWidth(2);
        canvas.rectangle(30, 30, pageWidth - 60, pageHeight - 60);
        canvas.stroke();

        // 绘制四个角
        float cornerSize = 40;

        // 左上角
        canvas.moveTo(30, 30 + cornerSize);
        canvas.lineTo(30, 30);
        canvas.lineTo(30 + cornerSize, 30);

        // 右上角
        canvas.moveTo(pageWidth - 30 - cornerSize, 30);
        canvas.lineTo(pageWidth - 30, 30);
        canvas.lineTo(pageWidth - 30, 30 + cornerSize);

        // 左下角
        canvas.moveTo(30, pageHeight - 30 - cornerSize);
        canvas.lineTo(30, pageHeight - 30);
        canvas.lineTo(30 + cornerSize, pageHeight - 30);

        // 右下角
        canvas.moveTo(pageWidth - 30 - cornerSize, pageHeight - 30);
        canvas.lineTo(pageWidth - 30, pageHeight - 30);
        canvas.lineTo(pageWidth - 30, pageHeight - 30 - cornerSize);

        canvas.stroke();
    }

    // 加载楷体字体的方法
    private BaseFont loadKaiFont(ClassLoader classLoader) {
        try {
            // 尝试从资源文件加载楷体
            try (InputStream fontStream = classLoader.getResourceAsStream("fonts/simkai.ttf")) {
                if (fontStream != null) {
                    byte[] fontData = IOUtils.toByteArray(fontStream);
                    return BaseFont.createFont("simkai.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, false, fontData, null);
                }
            }

            // 如果资源文件不存在，尝试使用系统字体
            try {
                return BaseFont.createFont("KaiTi", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            } catch (Exception e) {
                System.out.println("系统楷体不可用，尝试STKaiti");
            }

            // 尝试其他可能的楷体名称
            try {
                return BaseFont.createFont("STKaiti", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            } catch (Exception e) {
                System.out.println("STKaiti不可用，尝试其他字体");
            }

            // 尝试使用宋体作为备选
            try {
                return BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            } catch (Exception e) {
                System.out.println("宋体也不可用");
            }

            // 最后尝试使用默认字体
            return BaseFont.createFont();

        } catch (Exception e) {
            System.out.println("加载字体失败，使用默认字体"+e);
            try {
                return BaseFont.createFont();
            } catch (Exception ex) {
                throw new RuntimeException("无法创建字体", ex);
            }
        }
    }
}
